from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from typing import List, Dict, Any

app = FastAPI()

# 允许跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 存储主窗口引用
main_window = None


def set_main_window(window):
    global main_window
    main_window = window


@app.post("/run_script")
async def run_script(request: List[Dict[str, Any]]):
    print(request)
    if not main_window:
        raise HTTPException(status_code=500, detail="主程序未启动")
    try:
        # 通过主窗口运行脚本
        main_window.run_script_http.emit(request)
        return {"status": "success", "message": "脚本已运行"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

def start_server(port: int = 8080):
    uvicorn.run(app, port=port)
